package jp.co.apl.haven_enquete.android.dao;

import java.util.Date;
import java.util.List;
import java.util.Map;

import jp.co.apl.haven.generated.HavenProtos.BasicInfo;
import jp.co.apl.haven_enquete.android.db.DatabaseHelper;
import jp.dev7.android.util.Contexts;
import jp.dev7.android.util.Dbs;
import jp.dev7.android.util.Dbs.FuncCur;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.google.common.base.Function;
import com.google.common.collect.Maps;

public class BasicInfoDataDao {

    private final Context context;
    private final DatabaseHelper helper;

    public BasicInfoDataDao(Context context) {
        this.context = context;
        helper = new DatabaseHelper(context);
    }

    public List<BasicInfo> load() {
        SQLiteDatabase db = helper.getReadableDatabase();
        try {
            return Dbs.loadAsList(db, "BASIC_INFO", new FuncCur<BasicInfo>() {
                @Override
                public BasicInfo apply(Integer id, String value, Date updateAt) {
                    return BasicInfo
                        .newBuilder()
                        .setTerminalId(Contexts.getAndroidId(context))
                        .setBasicInfoItemId(id)
                        .setAnswer(value)
                        .setAnsweredDate(updateAt.getTime())
                        .build();
                }
            });
        } finally {
            db.close();
        }
    }

    public void save(final Map<Integer, String> map) {

        final SQLiteDatabase db = helper.getWritableDatabase();
        try {
            db.beginTransaction();

            Dbs.saveAll(db, "BASIC_INFO", map);

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    public Map<Integer, BasicInfo> loadAsMap() {
        return Maps.uniqueIndex(load(), new Function<BasicInfo, Integer>() {
            @Override
            public Integer apply(BasicInfo input) {
                return input.getBasicInfoItemId();
            }
        });
    }

}
